package com.sk.bilibili.service;

import com.sk.bilibili.bean.Danmu;
import com.sk.bilibili.dto.DanmuInfo;
import lombok.SneakyThrows;

import javax.websocket.Session;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author 邵康
 * @date 2021/12/2 15:57
 * 泛型为发送对象 一般一个请求 对象要统一 通过type区分 方便前端处理
 */
public abstract class BaseBroadcastSocketService<T> {

    protected Map<Integer, Set<Session>> sessionMap=new HashMap<>();

    public void addNew(Integer id, Session session) {
        if(!sessionMap.containsKey(id)){
            sessionMap.put(id,new HashSet<>());
        }
        Set<Session> sessions = sessionMap.get(id);
        sessions.add(session);
        afterAddNew(id,session);
    }

    protected abstract void afterAddNew(Integer id,Session session);

    @SneakyThrows
    public void broadcastMessage(Integer id,T message) {
        Set<Session> sessions = sessionMap.get(id);
        for (Session session:sessions){
            session.getBasicRemote().sendObject(message);
        }
    }

    public void removeOld(Integer id, Session session) {
        Set<Session> sessions = sessionMap.get(id);
        sessions.remove(session);
        afterRemove(id,session);
    }

    protected abstract void afterRemove(Integer id, Session session);

}
